package com.open.base.zookeeper;

import com.open.base.zookeeper.properties.ZookeeperProperty;
import lombok.Getter;
import lombok.Setter;
import org.apache.curator.RetryPolicy;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.framework.recipes.cache.CuratorCache;
import org.apache.curator.retry.ExponentialBackoffRetry;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;

/**
 * zookeeper 配置类
 */
@EnableConfigurationProperties(ZookeeperProperty.class)
@ComponentScan
public class ZookeeperAutoConfiguration {


    @Bean(initMethod = "start",destroyMethod = "close")
    @ConditionalOnMissingBean
    public CuratorFramework curatorFramework(ZookeeperProperty zookeeperProperty){
        RetryPolicy retryPolicy = new ExponentialBackoffRetry(zookeeperProperty.getBaseSleepTime(),zookeeperProperty.getMaxRetries());
        return CuratorFrameworkFactory.builder()
                .connectString(zookeeperProperty.getConnectString())
                .connectionTimeoutMs(zookeeperProperty.getConnectionTimeout())
                .sessionTimeoutMs(zookeeperProperty.getSessionTimeout())
                .retryPolicy(retryPolicy).build();
    }
}
